/**
  ******************************************************************************
  * @file    mg_driver_pwm.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2019 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */

#include "mg_driver_pwm.h"
#include "mg_driver_clock.h"
#include "mg_driver_gpio.h"

void PWM_Init(u16 PwmIdx, u32 CountInit, u32 DurCount)
{
    //to do clock gating
    CLK_SetClockGate(CLK_GATE_PWM_EN);
    
    //to do pin mux & cfg
    if(PwmIdx > PWM_CH4)return; //error
    if(!DurCount)return;
    
    if(PwmIdx == PWM_CH0)//GPA11
    {
        GPIO_FunctionSelect(GPIO_MAP_PIN_A11, GPIO_MAP_PIN_FUNC2);
        SysCtrl->PA_CONF[11] = 0x04; // GPIO Push-Pull mode
    }
    else if(PwmIdx == PWM_CH1)//GPA12
    {
        GPIO_FunctionSelect(GPIO_MAP_PIN_A12, GPIO_MAP_PIN_FUNC2);
        SysCtrl->PA_CONF[12] = 0x04; // GPIO Push-Pull mode
    }
    else if(PwmIdx == PWM_CH2)//GPA13
    {
        GPIO_FunctionSelect(GPIO_MAP_PIN_A13, GPIO_MAP_PIN_FUNC2);
        SysCtrl->PA_CONF[13] = 0x04; // GPIO Push-Pull mode
    }
    else if(PwmIdx == PWM_CH3)//GPA14
    {
        GPIO_FunctionSelect(GPIO_MAP_PIN_A14, GPIO_MAP_PIN_FUNC2);
        SysCtrl->PA_CONF[14] = 0x04; // GPIO Push-Pull mode
    }
    else if(PwmIdx == PWM_CH4)//GPA10
    {
        GPIO_FunctionSelect(GPIO_MAP_PIN_A10, GPIO_MAP_PIN_FUNC2);    
        SysCtrl->PA_CONF[10] = 0x04; // GPIO Push-Pull mode
    }
    
    PWM->cfg[PwmIdx].PWM_DUTY = CountInit;
    PWM->cfg[PwmIdx].PWM_DIV  = DurCount-1;
}

void PWM_SetValue(u16 PwmIdx,u32 DutyValue)
{
    if(PwmIdx > PWM_CH4)return; //error
    
    PWM->cfg[PwmIdx].PWM_DUTY = DutyValue;
}

void PWM_SetEnable(u8 EnableBitMap) //[EnableBitMap] can be one of {PWM_EN_CHx,PWM_DISABLE}
{
    //clock gating
    //to do...
    if(!EnableBitMap)
    {
        //to do...
    }

    PWM->PWM_ENABLE = EnableBitMap;
}

void PWM_SetClockDiv(u16 Div)
{
    if(Div)
    {
        PWM->PWM_CLK_DIV_1 = Div-1;
    }
}

